const koa = require('koa');
const redis = require('redis');
const session = require('koa-session');
const redisStore = require('koa-redis');
const wrapper = require('co-redis');

// 创建 koa 实例
const app = new koa();

// redis 配置
const redisClient = redis.createClient(6379, 'localhost');
const client = wrapper(redisClient);

// cookie 加密 key
app.keys = ['some secret'];

// session 配置
const SESSION_CONFIG = {
    key: 'sid', // 名
    // maxAge: 8640000, // 有效期
    // httpOnly: true, // 服务器有效
    // signed: true // 签名
    store: redisStore({ client }),
};

// 使用 session
app.use(session(SESSION_CONFIG, app));

// 测试
app.use(async (ctx) => {
    if (ctx.path === '/favicon.ico') return;
    let count = ctx.session.count || 0;
    ctx.session.count = ++count;
    ctx.body = '第' + count + '次访问';
});

app.listen(3000);

// 查看 redis 中的值
redisClient.keys('*', (err, keys) => {
    console.log('keys:', keys);
    keys.forEach((key) => {
        redisClient.get(key, (err, val) => {
            console.log(val);
        });
    });
});
